import { JSEncrypt } from 'jsencrypt'

const rsaPublicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCk+8ad8AvD2LOH7uQhksZTpvY95eoBHBS3gKT6eYBuSR4FgFfCvPJzHO1mi09OGx59L1TRBxtpFwvP5b6YijMNL/BJfHhgqbJT8kdWlaYOt3WchCQkcqOHwNGJaU1mUNJj0eK+WsFBxOHsmy/cXL1waIeyPfDiLfbp67iyRqCl1wIDAQAB'
const sm2PublicKey = '041555461f4b6c33989f86a5547ef395e8b0ef0c30762bfb04e42cc4e6f268ff0c63d7a68663173c73685e384b0f3f4d26b1f26c03b4a67a45909c78127e8cbd3e'

export function encryptText (text, encryptType) {
  const list = []
  for (let i = 0; i < text.length; i += 50) {
    list.push(text.slice(i, i + 50))
  }
  return list.map(s => encrypt(s, encryptType)).join(',')
}

const encryptor = new JSEncrypt()
encryptor.setPublicKey(rsaPublicKey)

const sm2 = require('sm-crypto').sm2

function encrypt (str, encryptType) {
  if (encryptType === '1' || encryptType === 'RSA') {
    return encryptor.encrypt(str)
  }
  if (encryptType === 'SM2') {
    return '04' + sm2.doEncrypt(str, sm2PublicKey)
  }
}
